<template>
    <div>
        <el-row :gutter="20">
            <el-col :span="12">
                <el-card shadow="hover" class="mgb20" style="height:712px;">
                    <div slot="header" class="clearfix">
                        <span>智能分析</span>
                    </div>
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="分析目标" prop="goal">
                            <el-input type="textarea" v-model="ruleForm.goal"></el-input>
                        </el-form-item>

                        <el-form-item label="图表名称" prop="name">
                            <el-input v-model="ruleForm.name"></el-input>
                        </el-form-item>

                        <el-form-item label="图表类型" prop="chartType">
                            <el-select v-model="ruleForm.chartType" placeholder="请选择图表类型">
                            <el-option label="柱状图" value="柱状图"></el-option>
                            <el-option label="折线图" value="折线图"></el-option>
                            <el-option label="堆叠图" value="堆叠图"></el-option>
                            <el-option label="饼图" value="饼图"></el-option>
                            <el-option label="雷达图" value="雷达图"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="原始数据" prop="file">
                            <el-upload class="upload-demo"
                            action="#"
                            :limit="1"
                            :on-exceed="handleExceed"
                            :auto-upload="false"
                            :multiple="false"
                            ref="uploadExcel"           
                            :http-request="uploadFile">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div slot="tip" class="el-upload__tip">{{message}}</div>
                            </el-upload>
                        </el-form-item>
                        
                        <el-form-item>
                            <el-button type="primary" :loading="submitLoading" @click="submitEditForm('ruleForm')">提交</el-button>
                            <el-button @click="resetForm('ruleForm')">重置</el-button>
                        </el-form-item>
                        </el-form>
                </el-card>
                
            </el-col>
            <el-col :span="12">
                <el-card shadow="hover" style="margin-bottom: 5%;">
                    <div slot="header" class="clearfix">
                        <span>分析结论</span>
                    </div>
                    <p v-loading = "resultLoading">{{genResult}}</p>
                    <div>
                        
                    </div>
                </el-card>

                <el-card shadow="hover" style="">
                    <div slot="header" class="clearfix">
                        <span>可视化图表</span>
                    </div>
                    <div id="myChart" v-loading="chartLoading" :style="{ }">

                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import Schart from 'vue-schart';
import bus from '../common/bus';
import { InfiniteScroll } from "element-ui"
import { getNoticeList, getLoginUser,getContestList, genChartByAiAsync, getChartById } from '../../api';
// import echarts from 'echarts'
       
export default {
    name: 'dashboard',
    directives: {
        	"infinite-scroll": InfiniteScroll,
     },
    data() {
        return {
            submitLoading: false,
            resultLoading: false,
            chartLoading: false,
            //上传
            headers: {
            "content-type": "multipart/form-data"
            },
            message: '请上传 xls/xlsx 或 csv 文件',
            file: {},
            genResult:'',
            genChart:{},

            ruleForm: {
                name: '',
                goal: '',
                chartType: ''
                },
                rules: {
                chartType: [
                    { required: true, message: '请选择图表类型', trigger: 'change' }
                ],
                goal: [
                    { required: true, message: '请填写分析目标', trigger: 'blur' }
                ],
            },
            
            userInfo:{}
        };
    },
    components: {
        Schart
    },
    computed: {
        // role() {
        //     return this.name === this.userInfo.userRole
        // },
    },
    mounted(){
        // this.drawLine();
    },
    created() {
        getLoginUser().then(res => {
            console.log("智能分析")
            console.log(res)
            if(res.code == 40100) {
                this.$message.error("用户未登录，请登录！")
                this.$router.push('/login')
            }else{
                this.userInfo=res.data
            }
        })
    },
    methods: {
        drawLine(){
            // 基于准备好的dom，初始化echarts实例
            let echarts = require('echarts');
            let myChart = echarts.init(document.getElementById('myChart'))
            // 绘制图表
            myChart.setOption(this.genChart);
        },
        
          //自定义上传方法，使用上传组件的submit()后才会触发以获取文件实体
        uploadFile(param) {
            this.file = param.file;
        },
        
        //上传文件+表单数据
        submitEditForm() {
            this.$refs.uploadExcel.submit();
            //携带文件必须使用此对象
            const formDatas = new FormData(); 
            if (this.file) {
                //append方法逐个添加键值对
                formDatas.append("file", this.file); //把文件实体添加到表单对象
            }
            //添加收集的表单数据
            // this.addForm = this.form
            // //序列化其他数据为json添加到表单对象，后台反序列化获取对象实体，也可以单个append(),后台直接用对象取，如果一次性添加而不序列化会出错
            // formDatas.append("form", JSON.stringify(this.addForm));
            formDatas.append("name", this.ruleForm.name);
            formDatas.append("goal", this.ruleForm.goal);
            formDatas.append("chartType", this.ruleForm.chartType);
            console.log(formDatas)
            //将数据随请求发过去
            // this.addTrans(formDatas);
            this.submitLoading=true
            this.resultLoading=true
            this.chartLoading=true
            genChartByAiAsync(formDatas).then(res => {
                console.log(res)
                this.getChart(res.data.chartId)
            })
        },
        getChart(id){
            let  timer = setInterval(() => {
                this.fun(timer,id)
            }, 2000)
        },
        fun (timer,chartId) {//图表id
         setTimeout(()=>{
          // 这里ajax 请求的代码片段和判断是否停止定时器
            //根据图表id不断查询，直到状态发生变化
            const params = {
                id:Number
            }
            params.id=chartId
            getChartById(params).then(response => {
                let res = response.data
                if(response.code != 0){
                    this.$message.error(response.message)
                    this.submitLoading=false
                    this.resultLoading=false
                    this.chartLoading=false
                    clearInterval(timer)
                    return;
                }
                if(res.status=='succeed'){
                    this.genResult=res.genResult
                    console.log(res.genChart)
                    this.genChart = eval("(" + res.genChart + ")");
                    this.drawLine();
                    this.submitLoading=false
                    this.resultLoading=false
                    this.chartLoading=false
                    clearInterval(timer)
                }else if(res.status == 'failed'){
                    this.genResult=res.execMessage
                    this.submitLoading=false
                    this.resultLoading=false
                    this.chartLoading=false
                    clearInterval(timer)
                }
            })
          // 如需要停止定时器，只需加入以下：
        //    clearInterval(timer)
            }, 0)
        },
        
        
        //限制上传文件数量
            handleExceed() {
            this.$alert("文件数量超过限制", {
                confirmButtonText: "确定",
            });
        },
        
        //重置
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.$refs.upload.clearFiles()
        },
    }
};
</script>


<style scoped>
.loading{
    text-align: center;
}
.loading span {
  display: inline-block;
  width: 35px;
  margin: 0 auto;
  height: 35px;
  border: 3px solid #409eff;
  border-left: transparent;
  animation: zhuan 0.5s linear infinite;
  border-radius: 50%;
}
@keyframes zhuan {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(360deg);
  }
}
.el-row {
    margin-bottom: 20px;
}

.grid-content {
    display: flex;
    align-items: center;
    height: 100px;
}

.grid-cont-right {
    flex: 1;
    text-align: center;
    font-size: 14px;
    color: #999;
}

.grid-num {
    font-size: 30px;
    font-weight: bold;
}

.grid-con-icon {
    font-size: 50px;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
    color: #fff;
}

.grid-con-1 .grid-con-icon {
    background: rgb(45, 140, 240);
}

.grid-con-1 .grid-num {
    color: rgb(45, 140, 240);
}

.grid-con-2 .grid-con-icon {
    background: rgb(100, 213, 114);
}

.grid-con-2 .grid-num {
    color: rgb(45, 140, 240);
}

.grid-con-3 .grid-con-icon {
    background: rgb(242, 94, 67);
}

.grid-con-3 .grid-num {
    color: rgb(242, 94, 67);
}

.user-info {
    display: flex;
    align-items: center;
    padding-bottom: 20px;
    border-bottom: 2px solid #ccc;
    margin-bottom: 20px;
}

.user-avator {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    cursor:pointer;
}

.user-info-cont {
    padding-left: 50px;
    flex: 1;
    font-size: 14px;
    color: #999;
}

.user-info-cont div:first-child {
    font-size: 30px;
    color: #222;
}

.user-info-list {
    font-size: 14px;
    color: #999;
    line-height: 25px;
}

.user-info-list span {
    margin-left: 70px;
}

.mgb20 {
    margin-bottom: 20px;
}

.todo-item {
    font-size: 14px;
}

.todo-item-del {
    text-decoration: line-through;
    color: #999;
}

.schart {
    width: 100%;
    height: 300px;
}
</style>
